package main.java.regression;

import java.util.ArrayList;
import java.util.List;
import main.java.message.Message;
import main.java.message.MessageContents;
import main.java.message.MessageListener;
import main.java.message.MessageSender;
import main.java.message.MessageTags;

public class Regression {
	private User creator;
	private User currentUser;
	private List<User> dataSourceUsers = new ArrayList<User>();
	private RegressionType regressionType;
	private RegressionHandler regressionHandler;
	private MessageListener msgListener;
	private List<Message> unackedMessage = new ArrayList<Message>();

	public User getCreator() {
		return creator;
	}

	public void setCreator(User creator) {
		this.creator = creator;
	}

	public User getCurrentUser() {
		return currentUser;
	}

	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}

	public List<User> getDataSourceUsers() {
		return dataSourceUsers;
	}

	public void setDataSourceUsers(List<User> dataSourceUsers) {
		this.dataSourceUsers = dataSourceUsers;
	}

	public RegressionType getRegressionType() {
		return regressionType;
	}

	public void setRegressionType(RegressionType regressionType) {
		this.regressionType = regressionType;
	}

	public RegressionHandler getRegressionHandler() {
		return regressionHandler;
	}

	public void setRegressionHandler(RegressionHandler regressionHandler) {
		this.regressionHandler = regressionHandler;
	}

	public List<Message> getUnackedMessage() {
		return unackedMessage;
	}

	public void setUnackedMessage(List<Message> unackedMessage) {
		this.unackedMessage = unackedMessage;
	}

	public void addUser(User user) {
		dataSourceUsers.add(user);
	}

	public synchronized void addUnackedMessage(Message message, User reciever) {
		message.setReciever(reciever);
		unackedMessage.add(message);
	}

	public synchronized void removeUnAckedMessage(String msgID) {
		for (Message msg : unackedMessage) {
			if (msg.getId().equals(msgID)) {
				unackedMessage.remove(msg);
				break;
			}
		}

	}

	public synchronized void resendUnackedMessage() {
		for (Message msg : unackedMessage) {
			MessageSender sender = new MessageSender(msg.getReciever());
			sender.sendMessage(msg.toString());
		}
	}

	public boolean startMessageListener() {
		if (currentUser == null)
			return false;
		msgListener = new MessageListener(currentUser.getPort(), this);
		(new Thread(msgListener)).start();
		return true;
	}

	public void pingUser(User user) {
		MessageSender sender = new MessageSender(user.getIp(), user.getPort());
		Message msg = new Message(MessageContents.PING);
		msg.put(MessageTags.ACK_REQUIRED, MessageContents.TRUE.getContent());
		sender.sendMessage(msg.toString());
		addUnackedMessage(msg, user);
	}

}
